//
//  BKImageBrowserView.m
//  BESTKEEP
//
//  Created by 武探 on 2016/9/27.
//  Copyright © 2016年 YISHANG. All rights reserved.
//

#import "BKGDImageBrowserView.h"

@interface BKGDImageBrowserViewCell : UICollectionViewCell

@property(nonatomic,strong) UIImageView *imageView;

@end

@implementation BKGDImageBrowserViewCell

-(instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if(self) {
        [self initialize];
    }
    return self;
}

-(void)initialize {
    
    _imageView = [[UIImageView alloc] init];
    _imageView.contentMode = UIViewContentModeScaleAspectFill;
    [self.contentView addSubview:_imageView];
}

-(void)layoutSubviews {
    [super layoutSubviews];
    _imageView.frame = CGRectMake(5, 0, CGRectGetWidth(self.frame) - 10, CGRectGetHeight(self.frame));
}

@end







NSString *const BKGDImageBrowserViewCellIdentifier = @"BKGDImageBrowserViewCellIdentifier";

@interface BKGDImageBrowserView()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UIGestureRecognizerDelegate>

@property(nonatomic,assign,readonly) CGRect collectionViewFrame;
@property(nonatomic,strong) UICollectionView *collectionView;

@property(nonatomic,strong) UIPageControl *pageControl;

@end

@implementation BKGDImageBrowserView

-(instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if(self) {
        [self initialize];
    }
    return self;
}

-(void)initialize {
    
    _currentIndex = 0;

    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.itemSize = self.collectionViewFrame.size;
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    
    _collectionView = [[UICollectionView alloc] initWithFrame:self.collectionViewFrame collectionViewLayout:layout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.pagingEnabled = YES;
    _collectionView.showsHorizontalScrollIndicator = NO;
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.bounces = NO;
    _collectionView.scrollsToTop = NO;
    _collectionView.backgroundColor = [UIColor clearColor];
    [_collectionView registerClass:[BKGDImageBrowserViewCell class] forCellWithReuseIdentifier:BKGDImageBrowserViewCellIdentifier];
    [self addSubview:_collectionView];
    
    _pageControl = [[UIPageControl alloc] init];
    _pageControl.pageIndicatorTintColor = [UIColor grayColor];
    _pageControl.currentPageIndicatorTintColor = [UIColor colorWithRed:0.314 green:0.784 blue:0.686 alpha:1.00];
    _pageControl.hidesForSinglePage = YES;
    [_pageControl addTarget:self action:@selector(pageAction) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_pageControl];
    
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
    pan.delegate = self;
    [_collectionView addGestureRecognizer:pan];
}

-(CGRect)collectionViewFrame {
    CGRect frame = CGRectMake(-5, 0, CGRectGetWidth(self.frame) + 10, CGRectGetHeight(self.frame));
    return frame;
}

-(void)layoutSubviews {
    [super layoutSubviews];
    
    _collectionView.frame = self.collectionViewFrame;
    _pageControl.frame = CGRectMake(0, CGRectGetHeight(self.frame) - 40, CGRectGetWidth(_collectionView.frame), 20);
}

#pragma -mark collectionView delegate

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if(_images) {
        return _images.count;
    }
    return 0;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return self.collectionViewFrame.size;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    BKGDImageBrowserViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:BKGDImageBrowserViewCellIdentifier forIndexPath:indexPath];
    
    NSString *item = _images[indexPath.row];
    cell.imageView.contentMode = UIViewContentModeCenter;
    UIImage *image = [UIImage imageNamed:@"BKGDDefaultBigest"];
    __weak typeof(cell) weakCell = cell;
    if (![_goodsCoverImg isEqualToString:@""] && indexPath.row == 0) {
        weakCell.imageView.contentMode = UIViewContentModeScaleAspectFill;
        weakCell.imageView.image = [CacheImage imageFromKey:_goodsCoverImg];
    }else{
        [cell.imageView load:item placeholderImage:image progress:nil completed:^(UIImage *image, NSError *error, NSURL *imageURL) {
            if(image) {
                weakCell.imageView.contentMode = UIViewContentModeScaleAspectFill;
                weakCell.imageView.image = image;
            }
        }];
    }
    return cell;
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    NSInteger page = scrollView.contentOffset.x / CGRectGetWidth(scrollView.frame);
    _pageControl.currentPage = page;
}

-(void)pageAction{
     [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:_pageControl.currentPage inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
}

-(void)setImages:(NSArray<NSString *> *)images {
    _images = images;
    _pageControl.numberOfPages = _images.count;
}

-(void)setCurrentIndex:(NSInteger)currentIndex {
    
    if(!_images || _images.count == 0) {
        _currentIndex = 0;
        return;
    }
    
    _currentIndex = currentIndex <= 0 ? 0 : currentIndex > _images.count ? _images.count - 1 : currentIndex;
    _pageControl.currentPage = _currentIndex;
}

-(void)refresh {
    
    [_collectionView.collectionViewLayout invalidateLayout];
    
    [_collectionView reloadData];

    if(_images) {
        [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:_currentIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
    }
}

#pragma -mark gestureRecognizer

-(BOOL)gestureRecognizerShouldBegin:(UIPanGestureRecognizer *)gestureRecognizer {
    CGPoint point = [gestureRecognizer translationInView:_collectionView];
    if(point.x < 0) {
        
        NSInteger page = _collectionView.contentOffset.x / CGRectGetWidth(_collectionView.frame);
        _pageControl.currentPage = page;
        if(page >= _images.count - 1) {
            _collectionView.scrollEnabled = NO;
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(200 * NSEC_PER_MSEC)), dispatch_get_main_queue(), ^{
                _collectionView.scrollEnabled = YES;
            });
        }
    }
    
    return NO;
}

-(void)pan:(UIGestureRecognizer*)recognizer {
    
}

@end
